layui.define(['zlContext', 'layer', 'zlConfig'], function (exports) {
    var $ = layui.$,
        zlContext = layui.zlContext,
        zlConfig = layui.zlConfig,
        statusName = zlConfig.global.result.statusName,
        dataName = zlConfig.global.result.dataName,
        OK = zlConfig.global.result.okState,
        treeObj = null;

    var zltreemenu = {
        isloadsearch: false,
        isExpand: false,
        options: {},
        callback: {},
        /**
         * @param {*} id  目标ul ID 值
         * @param {*} setting   zTree 自定义配置项  需是对象
         * @param {*} callback   zTree 各回调函数
         */
        render: function (id, setting, callback) {
            var defaultOptions = { // 默认配置项
                name: 'OBJNAME', // zTree 节点数据保存节点名称的属性名称
                type: 'post', // Ajax 的 http 请求模式
                idKey: 'RWID', // 节点数据中保存唯一标识的属性名称
                pIdKey: 'SYS_PARENTID', // 节点数据中保存其父节点唯一标识的属性名称
                rootPid: null, // 用于修正根节点父节点数据，即 pIdKey 指定的属性值
                autoParam: [], // 异步加载时需要自动提交父节点属性的参数
                otherParam: {}, // Ajax 请求提交的静态参数键值对
                isCopy: false, // 拖拽时, 设置是否允许复制节点
                isMove: true, // 拖拽时, 设置是否允许移动节点
                prev: true, // 拖拽到目标节点时，设置是否允许移动到目标节点前面的操作
                next: true, // 拖拽到目标节点时，设置是否允许移动到目标节点后面的操作
                editEnable: true, // 设置 zTree 是否处于编辑状态
                showRemoveBtn: false, // 设置是否显示删除按钮
                showRenameBtn: false, // 设置是否显示编辑名称按钮
                checkEnable: false,
                chkStyle: "checkbox",
                chkboxType: {
                    "Y": "ps",
                    "N": "ps"
                },
                zNodes:[],
                // autoCheckTrigger: false,
                // nocheckInherit: false,
                // chkDisabledInherit: false,
                // radioType: "level",
                search: true, // 是否开启搜索功能
                // asyncSearch: false,
                asyncChildNodes: false // 1.zTree 的节点父节点属性锁，是否始终保持 isParent = true 2.作为搜索方式的判断依据
                // 详细参数说明可查看zTree API文档 ： http://www.treejs.cn/v3/api.php
            };

            if (zltreemenu.options[id]) {
                zltreemenu.options[id] = $.extend({}, zltreemenu.options[id], setting);
            } else {
                zltreemenu.options[id] = $.extend({}, defaultOptions, setting);
            }

            zltreemenu.callback[id] = $.extend({}, zltreemenu.callback[id], callback);

            var zltreeSetting = {
                view: {
                    showLine: true,
                    fontCss: zltreemenu.options[id].fontCss ? zltreemenu.options[id].fontCss : {}
                },
                async: {
                    enable: true,
                    url: zltreemenu.options[id].dataurl,
                    type: zltreemenu.options[id].type,
                    autoParam: zltreemenu.options[id].autoParam,
                    otherParam: zltreemenu.options[id].otherParam,
                    contentType: (zltreemenu.options[id].contentType ? zltreemenu.options[id].contentType : 'application/x-www-form-urlencoded'),
                    dataType: "json",
                    dataFilter: zltreemenu.options[id].dataFilter ? zltreemenu.options[id].dataFilter : zltreemenu.dataFilter
                },
                check: {
                    enable: zltreemenu.options[id].checkEnable,
                    chkStyle: zltreemenu.options[id].chkStyle,
                    chkboxType: zltreemenu.options[id].chkboxType,
                },
                data: {
                    keep: {
                        leaf: false,
                        parent: zltreemenu.options[id].asyncChildNodes,
                    },
                    key: {
                        name: zltreemenu.options[id].name
                    },
                    simpleData: {
                        enable: true,
                        idKey: zltreemenu.options[id].idKey,
                        pIdKey: zltreemenu.options[id].pIdKey,
                        rootPid: zltreemenu.options[id].rootPid
                    }
                },
                edit: {
                    drag: {
                        isCopy: zltreemenu.options[id].isCopy,
                        isMove: zltreemenu.options[id].isMove,
                        prev: zltreemenu.options[id].prev,
                        next: zltreemenu.options[id].next,
                        inner: zltreemenu.options[id].inner
                    },
                    enable: zltreemenu.options[id].editEnable,
                    showRemoveBtn: zltreemenu.options[id].showRemoveBtn,
                    showRenameBtn: zltreemenu.options[id].showRenameBtn,
                },
                callback: zltreemenu.callback[id]
            };

            // 搜索部分 dom
            var searchHtml = [
                '<div class="layui-form-item layui-search zltreeMenuSearch">',
                '   <div class="layui-input-block">',
                '       <input id="btnTreeSearchInput" type="text" name="search" data-boxid="' + id + '" placeholder="请输入查找的值" class="layui-input">',
                '       <a href="javascript:;" id="btnTreeSearch" style="">',
                '           <i class="layui-icon layui-icon-search"></i>',
                '       </a></div></div>'
            ];
            if (zltreemenu.options[id].search && $('#' + id).parent('div').siblings('div.layui-search').length == 0) { // 开启搜索功能后 搜索框渲染
                $('#' + id).parent('div').before(searchHtml.join(''))
            }

            // 树形菜单
            // 获取属性菜单的静态数据
            var getzNodes = zltreemenu.options[id].zNodes
            treeObj = $.fn.zTree.init($('#' + id), zltreeSetting, getzNodes);
            return treeObj;
        },
        search: function (value, type, id) {
            // 一次性加载所有数据时
            if (!type) {
                zltreemenu.isloadsearch = true;
                treeObj = $.fn.zTree.getZTreeObj(id);
                // 首先显示所有已隐藏的项
                treeObj.showNodes(treeObj.getNodesByParam("isHidden", true))
                if (value == '') {
                    $('#' + id).find('.noResultBox').remove();
                    var firstNode = treeObj.getNodesByFilter(function (node) {
                        return node.level == 0 && node.isFirstNode;
                    });
                    if (firstNode.length > 0) {
                        treeObj.selectNode(firstNode[0]);
                        $("#" + firstNode[0].tId + "_a").click();
                        $('#' + id).parents('.zltree-body').scrollTop(0)
                    }
                    if ($('ul#roletree').length > 0) {
                        $('ul#roletree').find('li').show();
                        $('ul#roletree').siblings('.noResultBox').remove();
                        $('ul#authtree').find('li').show();
                        $('ul#authtree').find('div.layui-none').remove();
                    }
                    return;
                }
                // 所有无子节点的节点
                var noChildrenNodes = treeObj.getNodesByParam("isParent", false);
                // 先隐藏所有，满足条件的节点显示
                treeObj.hideNodes(noChildrenNodes)
                treeObj.expandAll(true);
                treeObj.showNodes(treeObj.getNodesByFilter(function (noChildrenNodes) {
                    return noChildrenNodes.check_Child_State == -1 && noChildrenNodes[treeObj.setting.data.key.name].indexOf(value) > -1
                }));
                // 将没有子节点显示的父级节点也隐藏掉
                // 先获取所有父级节点
                setTimeout(function () {
                    var pNodes = treeObj.getNodesByParam("isParent", true);
                    pNodes.sort(compare('level'))
                    for (var i = 0; i < pNodes.length; i++) {
                        if (pNodes[i].children.length != 0) {
                            var hideNum = 0;
                            for (var k = 0; k < pNodes[i].children.length; k++) {
                                var item = pNodes[i].children[k];
                                if (item.isHidden == true) {
                                    hideNum++;
                                }
                            }
                            if (hideNum == pNodes[i].children.length && pNodes[i][treeObj.setting.data.key.name].indexOf(value) == -1) {
                                treeObj.hideNode(pNodes[i])
                            }
                        }
                    }
                    if (treeObj.getNodesByParam("isHidden", false).length == 0) {
                        // zlContext.warnMsg('没有搜索到相关数据');
                        if ($('#' + id).find('.noResultBox').length == 0) {
                            $('#' + id).append(zltreemenu.noresult)
                        }
                        zltreemenu.isHideTableData(zltreemenu.options[id].tableId, false);
                        // 角色权限管理页面 搜索显示
                        if ($('ul#roletree').length > 0) {
                            $('ul#roletree').find('li').hide();
                            if($('ul#roletree').siblings('div.noResultBox').length==0){
                                $('ul#roletree').after(zltreemenu.noresult);
                            }                            
                            $('ul#authtree').find('li').hide();
                            zlContext.noData($('ul#authtree'))
                        }
                    } else {
                        if ($('ul#roletree').length > 0) {
                            $('ul#roletree').find('li').show();
                            $('ul#roletree').siblings('.noResultBox').remove();
                            $('ul#authtree').find('li').show();
                            $('ul#authtree').find('div.layui-none').remove();
                        }
                        zltreemenu.isHideTableData(zltreemenu.options[id].tableId, true);
                        $('#' + id).find('.noResultBox').remove();
                        var firstNode = treeObj.getNodesByFilter(function (node) {
                            return node.level == 0 && node.isFirstNode;
                        });
                        if (firstNode.length > 0) {
                            treeObj.selectNode(firstNode[0]);
                            $("#" + firstNode[0].tId + "_a").click();
                            $('#' + id).parents('.zltree-body').scrollTop(0)
                        }
                    }
                    $('#btnTreeSearchInput').focus();
                }, 0)
            } else {
                zltreemenu.searchNodesByFuzzy(value);
            }
        },
        searchNodesByFuzzy: function (keyvalue) {
            if (keyvalue) {
                if (zltreemenu.options[treeObj.setting.treeId].flag == 'coreuser') {
                    treeObj.setting.async.url = layui.cache['contentPath'] + '/admin/coreorg/queryorgdepttree?resId=252177907A6047E38FC5F1D2E63F15C4';
                    treeObj.setting.async.otherParam = {
                        'keyvalue': keyvalue,
                        'isnotuseddept': false
                    };
                } else {
                    treeObj.setting.async.url = zltreemenu.options[treeObj.setting.treeId].searchurl;
                    treeObj.setting.async.otherParam[zltreemenu.options[treeObj.setting.treeId].searchKey] = keyvalue;
                }
                zltreemenu.isloadsearch = true;
            } else {
                if (zltreemenu.options[treeObj.setting.treeId].flag == 'coreuser') {
                    treeObj.setting.async.url = layui.cache['contentPath'] + '/admin/coreorg/queryorgdepttreelistbyparentid?resId=252177907A6047E38FC5F1D2E63F15C4';
                    treeObj.setting.async.otherParam = {
                        "startflag": "1"
                    };
                } else {
                    treeObj.setting.async.url = zltreemenu.options[treeObj.setting.treeId].dataurl;
                    treeObj.setting.async.otherParam = {};
                }
                zltreemenu.isloadsearch = false;
            }
            treeObj = $.fn.zTree.init($('#' + treeObj.setting.treeId), treeObj.setting, null);
            
            $('#btnTreeSearchInput').focus();
        },
        dataFilter: function (treeId, parentNode, responseData) {
            if (responseData[statusName] == OK) {
                return responseData[dataName];
            } else {
                zlContext.errorMsg(responseData[msgName]);
            }
            return responseData;
        },
        /**
         * 隐藏表格已有内容，显示无数据
         * id: 目标表格的 id 值
         */
        isHideTableData: function (id, flag) {
            var idArr = id.split('|');
            for (var i = 0; i < idArr.length; i++) {
                if (flag) {
                    $('#' + idArr[i]).siblings('div').find('div.layui-table-main').find('table').show();
                    $('#' + idArr[i]).siblings('div').find('div.layui-table-main').find('div.layui-none').hide();
                    $('#' + idArr[i]).siblings('div').find('div.layui-table-page').show();
                    $('#' + idArr[i]).siblings('div').find('div.layui-table-fixed').show();
                } else {
                    $('#' + idArr[i]).siblings('div').find('div.layui-table-main').find('table').hide();
                    zlContext.noData($('#' + idArr[i]).siblings('div').find('div.layui-table-main'));
                    $('#' + idArr[i]).siblings('div').find('div.layui-table-page').hide();
                    $('#' + idArr[i]).siblings('div').find('div.layui-table-fixed').hide();
                }
            }
        },
        noresult: '<div class="noResultBox">' +
            '   <i class="layui-icon layui-icon-about" style="font-size: 20px;vertical-align: sub;color: #f39b12;"></i>   ' +
            '   <span>没有搜索到相关数据</span>' +
            '</div>'
    }

    $(document).on('click', 'div.zltreeMenuSearch>div>a', function () {
        var id = $(this).siblings('input').attr('data-boxid');
        zltreemenu.search($(this).siblings('input').val(), zltreemenu.options[id].asyncChildNodes, id);
    })

    $(document).on('keyup', 'div.zltreeMenuSearch>div>input', function (e) {
        var id = $(this).attr('data-boxid');
        if (e.keyCode == '13') {
            zltreemenu.search($(this).val(), zltreemenu.options[id].asyncChildNodes, id)
        }
        if ((e.keyCode == '46' || e.keyCode == '8' || (e.ctrlKey && e.keyCode == '86')) && $(this).val() == '') {
            if (!zltreemenu.isloadsearch) return;
            $(this).siblings('a').trigger('click');
            $('#btnTreeSearchInput').focus();
        }
    })

    function compare(property) {
        return function (a, b) {
            var value1 = a[property],
                value2 = b[property];
            return value2 - value1;
        }
    }

    exports('zltreemenu', zltreemenu);
});